package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private  DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    /**
     * 新增菜品以及对应口味
     * @param dishDTO
     */
    @Transactional //开启事务
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        // 将dishDTO中的属性拷贝到dish中
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1数据
        dishMapper.insert(dish);
        // 获取inset语句生成的id
        Long dishId = dish.getId();
        //向口味表插入N条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //批量插入数据
            dishFlavorMapper.insertBatch(flavors);
        }
        //创建时间
        dish.setCreateTime(LocalDateTime.now());
         //更新时间
        dish.setUpdateTime(LocalDateTime.now());
        //创建人
        dish.setCreateUser(BaseContext.getCurrentId());
        //更新人
        dish.setUpdateUser(BaseContext.getCurrentId());
    }
}
